﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Agents.Admin
{
    //page for creating a new category for products
    public partial class NewCategory : System.Web.UI.Page
    {
        #region Event Handlers

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        //function is activated when the ok button is pressed
        protected void okBtn_Click(object sender, EventArgs e)
        {
            //print message if there was no input
            if (nameTxtbox.Text == "")
            {
                empty.Text = "לא הוכנס קלט";
            }
            else
            {
                Queries queries = new Queries();

                if (queries.CategoryExists(nameTxtbox.Text))
                {
                    empty.Text = "קטגוריה כבר קיימת.";
                }
                else
                {
                    // Disable the buttons so the user can't interfere
                    backBtn.Enabled = false;
                    okBtn.Enabled = false;

                    //updating the new category to the database
                    queries.AddCategory(nameTxtbox.Text);

                    // Announce success and wait for 2 seconds before redirecting
                    empty.Text = "הקטגוריה נוספה בהצלחה";
                    redirectionTimer.Enabled = true;
                }
            }
        }

        //function for redirecting the administrater back to his homepage without adding a category.
        protected void backBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect(GetReturnUrl());
        }

        /// <summary>
        /// Redirect back to the admin menu after a few seconds
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void redirectionTimer_Tick(object sender, EventArgs e)
        {
            Response.Redirect(GetReturnUrl());
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Get the return URL from the parameters
        /// </summary>
        /// <returns></returns>
        private String GetReturnUrl()
        {
            String returnUrl = "~/Admin/AdminMenu.aspx";

            if (Request.QueryString["ReturnUrl"] != null)
            {
                returnUrl = Request.QueryString["ReturnUrl"];
            }

            return returnUrl;
        }

        #endregion
    }
}